package per.zhy.demo.apple;

import com.alibaba.fastjson.JSONObject;
import net.sourceforge.tess4j.TesseractException;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.jsoup.helper.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhy on 2018/4/26.
 */
public class RegAppleAcct {
    private static final Logger logger = LoggerFactory.getLogger(RegAppleAcct.class);

    private void setData(AppleCookie appleCookie) {
        appleCookie.setEmail("dream5@maildu.de");
        appleCookie.setPwd("Zhybb2010");
        appleCookie.setFirstname("Frank");
        appleCookie.setLastname("Zheng");
        appleCookie.setBirthday("1994-07-21");
    }

    public static void main(String args[]) throws IOException, TesseractException, InterruptedException {
        AppleCookie appleCookie = new AppleCookie();

        RegAppleAcct regAppleAcct = new RegAppleAcct();

        System.out.println("准备进入页面...");
        regAppleAcct.setData(appleCookie);
        String[] data = regAppleAcct.getInfo();//进入页面
        appleCookie.setAidsp(data[0]);
        appleCookie.setScnt(data[1]);
        System.out.println("页面数据获取完成");

        TimeUnit.SECONDS.sleep(1);

        String code;
        do {
            new Captcha().getCaptcha(appleCookie);
            System.out.println("获取验证码完成,请输入code:");
            Scanner scanner = new Scanner(System.in);
            code = scanner.next();
        } while ("1".equals(code));

        appleCookie.setCaptcha_answer(code);

        System.out.println("验证密码中...");
        regAppleAcct.validatePass(appleCookie);


        //提交数据
        String entityStr = String.format(Data.DATA, appleCookie.getEmail(), appleCookie.getPwd(), appleCookie.getBirthday(), appleCookie.getFirstname(), appleCookie.getLastname(),
                appleCookie.getCaptcha_answer(), appleCookie.getCaptcha_id(), appleCookie.getCaptcha_token());
        System.out.println(entityStr);


        System.out.println("校验提交数据中...");
        String ret = regAppleAcct.verification(entityStr, appleCookie);
        if (StringUtil.isBlank(ret)) {
            System.out.println("验证信息校验通过 ");
        } else {
            System.out.println("验证信息校验不通过 : " + ret);
            System.exit(0);
        }


        String sendEmail_entity = String.format(Data.SEND_EMAIL, appleCookie.getEmail(), appleCookie.getFirstname(), appleCookie.getLastname());
        String sendRet = regAppleAcct.sendEmail(sendEmail_entity, appleCookie);
        JSONObject jsonObject = JSONObject.parseObject(sendRet);
        appleCookie.setEmail_id(jsonObject.getString("verificationId"));
        System.out.println("邮件已发送,请输入code:");
        Scanner scanner = new Scanner(System.in);
        String mailcode = scanner.next();
        appleCookie.setEmail_answer(mailcode);//
        System.out.println("邮箱验证中...");

        String validate_entity = String.format(Data.VAILDATE_EMAIL, appleCookie.getEmail(), appleCookie.getEmail_answer(), appleCookie.getEmail_id());
        System.out.println("邮箱验证实体 : " + validate_entity);
        regAppleAcct.validateEmail(validate_entity, appleCookie);


        System.out.println("完成注册中...");
        String final_enttiy = String.format(Data.FINISHREG_DATA, appleCookie.getEmail(), appleCookie.getPwd(), appleCookie.getBirthday(), appleCookie.getFirstname(), appleCookie.getLastname(),
                appleCookie.getEmail_answer(), appleCookie.getEmail_id());
        regAppleAcct.account(final_enttiy, appleCookie);

        Response capTchaResponse = Request.Get("https://appleid.apple.com/account/manage")
                .addHeader("User-Agent", "Mozilla/5.0 [en](Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36")
                .addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Referer", "https://appleid.apple.com/account")
                .execute();

        HttpResponse httpResponse = capTchaResponse.returnResponse();
        System.out.println(httpResponse.getStatusLine());
        String context = EntityUtils.toString(httpResponse.getEntity());
        System.out.println(context);
    }

    private void account(String final_enttiy, AppleCookie appleCookie) throws IOException {
        Response capTchaResponse = Request.Post("https://appleid.apple.com/account")
                .addHeader("User-Agent", "Mozilla/5.0 [en](Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36")
                .setHeader("X-Apple-ID-Session-Id", appleCookie.getAidsp())
                .setHeader("scnt", appleCookie.getScnt())
                .addHeader("Origin", "https://appleid.apple.com")
                .addHeader("X-Apple-I-FD-Client-Info", "{\"U\":\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36\",\"L\":\"zh-CN\",\"Z\":\"GMT+08:00\",\"V\":\"1.1\",\"F\":\"FOa44j1e3NlY5BSo9z4ofjb75PaK4Vpjt.gEngMQEjZrVglE4Ww.GEFF0Yz3ccbbJYMLgiPFU77qZoOSix5ezdstlYysrhsui6.IQnu3xgycUPm8LKfAaZ4pAJZ7OQuyPBB2SCXw2SCVL6yXyjaY1WMsiZRPrwVL6tqAhbrmQkLNbXky.7bc7.lzXJJIneGffLMC7EZ3QHPBirTYKUowRslzRQqwSM2V8htx1TqUJEhO3f9p_nH1uzjkD6myjaY2_GGEQIgwe98vDdYejftckuyPBDjaY2ftckZZLQ084akJmZxIFVCqv9_jpidPNs0ojpVMZ90L5H6fqUdHz15tTma1kxNGYjpjV2pNk0ug97SIVb40xN4t23f282p9KyP4yQhSFQ_v9NA14WX3NlY5DuY25BNnOVgw24uy.5f8\"}")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36")
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("X-Apple-Request-Context", "create")
                .addHeader("X-DevTools-Emulate-Network-Conditions-Client-Id", "(2E0AB4265CF3C9E9716F6466BAE7ADDA)")
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("X-Apple-Api-Key", "cbf64fd6843ee630b463f358ea0b707b")
                .addHeader("Referer", "https://appleid.apple.com/account")
                .addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Cookie", "idclient=web; dslang=CN-ZH; site=CHN; aidsp=" + appleCookie.getAidsp() + ";")
                .body(new StringEntity(final_enttiy, "UTF-8"))
                .execute();
        HttpResponse httpResponse = capTchaResponse.returnResponse();
        System.out.println(httpResponse.getStatusLine());
        if (httpResponse.getStatusLine().getStatusCode() == 201) {
            System.out.println("注册成功 \r\n账号 : " + appleCookie.getEmail() + "\r\n密码 : " + appleCookie.getPwd());
        } else {
            System.out.println("注册失败");
        }
        appleCookie.setScnt(httpResponse.getHeaders("scnt")[0].getValue());
    }

    private String sendEmail(String entity, AppleCookie appleCookie) throws IOException {
        Response capTchaResponse = Request.Post("https://appleid.apple.com/account/verification")
                .addHeader("User-Agent", "Mozilla/5.0 [en](Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36")
                .addHeader("X-Apple-ID-Session-Id", appleCookie.getAidsp())
                .addHeader("scnt", appleCookie.getScnt())
                .addHeader("Origin", "https://appleid.apple.com")
                .addHeader("X-Apple-I-FD-Client-Info", "{\"U\":\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36\",\"L\":\"zh-CN\",\"Z\":\"GMT+08:00\",\"V\":\"1.1\",\"F\":\"FOa44j1e3NlY5BSo9z4ofjb75PaK4Vpjt.gEngMQEjZrVglE4Ww.GEFF0Yz3ccbbJYMLgiPFU77qZoOSix5ezdstlYysrhsui6.IQnu3xgycUPm8LKfAaZ4pAJZ7OQuyPBB2SCXw2SCVL6yXyjaY1WMsiZRPrwVL6tqAhbrmQkLNbXky.7bc7.lzXJJIneGffLMC7EZ3QHPBirTYKUowRslzRQqwSM2V8htx1TqUJEhO3f9p_nH1uzjkD6myjaY2_GGEQIgwe98vDdYejftckuyPBDjaY2ftckZZLQ084akJmZxIFVCqv9_jpidPNs0ojpVMZ90L5H6fqUdHz15tTma1kxNGYjpjV2pNk0ug97SIVb40xN4t23f282p9KyP4yQhSFQ_v9NA14WX3NlY5DuY25BNnOVgw24uy.5f8\"}")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36")
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("X-Apple-Request-Context", "create")
                .addHeader("X-DevTools-Emulate-Network-Conditions-Client-Id", "(2E0AB4265CF3C9E9716F6466BAE7ADDA)")
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("X-Apple-Api-Key", "cbf64fd6843ee630b463f358ea0b707b")
                .addHeader("Referer", "https://appleid.apple.com/account")
                .addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Cookie", "idclient=web; dslang=CN-ZH; site=CHN; aidsp=" + appleCookie.getAidsp() + ";")
                .body(new StringEntity(entity, "UTF-8"))
                .execute();
        HttpResponse httpResponse = capTchaResponse.returnResponse();
        System.out.println(httpResponse.getStatusLine());
        appleCookie.setScnt(httpResponse.getHeaders("scnt")[0].getValue());
        return EntityUtils.toString(httpResponse.getEntity());
    }

    private void validateEmail(String entity, AppleCookie appleCookie) throws IOException {
        Response capTchaResponse = Request.Put("https://appleid.apple.com/account/verification")
                .addHeader("User-Agent", "Mozilla/5.0 [en](Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36")
                .addHeader("X-Apple-ID-Session-Id", appleCookie.getAidsp())
                .addHeader("scnt", appleCookie.getScnt())
                .addHeader("Origin", "https://appleid.apple.com")
                .addHeader("X-Apple-I-FD-Client-Info", "{\"U\":\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36\",\"L\":\"zh-CN\",\"Z\":\"GMT+08:00\",\"V\":\"1.1\",\"F\":\"FOa44j1e3NlY5BSo9z4ofjb75PaK4Vpjt.gEngMQEjZrVglE4Ww.GEFF0Yz3ccbbJYMLgiPFU77qZoOSix5ezdstlYysrhsui6.IQnu3xgycUPm8LKfAaZ4pAJZ7OQuyPBB2SCXw2SCVL6yXyjaY1WMsiZRPrwVL6tqAhbrmQkLNbXky.7bc7.lzXJJIneGffLMC7EZ3QHPBirTYKUowRslzRQqwSM2V8htx1TqUJEhO3f9p_nH1uzjkD6myjaY2_GGEQIgwe98vDdYejftckuyPBDjaY2ftckZZLQ084akJmZxIFVCqv9_jpidPNs0ojpVMZ90L5H6fqUdHz15tTma1kxNGYjpjV2pNk0ug97SIVb40xN4t23f282p9KyP4yQhSFQ_v9NA14WX3NlY5DuY25BNnOVgw24uy.5f8\"}")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36")
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("X-Apple-Request-Context", "create")
                .addHeader("X-DevTools-Emulate-Network-Conditions-Client-Id", "(2E0AB4265CF3C9E9716F6466BAE7ADDA)")
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("X-Apple-Api-Key", "cbf64fd6843ee630b463f358ea0b707b")
                .addHeader("Referer", "https://appleid.apple.com/account")
                .addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Cookie", "idclient=web; dslang=CN-ZH; site=CHN; aidsp=" + appleCookie.getAidsp() + ";")
                .body(new StringEntity(entity, "UTF-8"))
                .execute();
        HttpResponse httpResponse = capTchaResponse.returnResponse();

        System.out.println(httpResponse.getStatusLine());
        appleCookie.setScnt(httpResponse.getHeaders("scnt")[0].getValue());
        if (httpResponse.getStatusLine().getStatusCode() == 204) {
            System.out.println("邮箱校验通过");
        } else {
            System.out.println("邮箱校验失败");
            System.exit(0);
        }
    }

    private void validatePass(AppleCookie appleCookie) throws IOException {
        System.out.println("pwd : snct" + appleCookie.toString());
        Response capTchaResponse = Request.Post("https://appleid.apple.com/account/validate/password")
                .addHeader("User-Agent", "Mozilla/5.0 [en](Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36")
                .addHeader("X-Apple-ID-Session-Id", appleCookie.getAidsp())
                .addHeader("scnt", appleCookie.getScnt())
                .addHeader("Origin", "https://appleid.apple.com")
                .addHeader("X-Apple-I-FD-Client-Info", "{\"U\":\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36\",\"L\":\"zh-CN\",\"Z\":\"GMT+08:00\",\"V\":\"1.1\",\"F\":\"FOa44j1e3NlY5BSo9z4ofjb75PaK4Vpjt.gEngMQEjZrVglE4Ww.GEFF0Yz3ccbbJYMLgiPFU77qZoOSix5ezdstlYysrhsui6.IQnu3xgycUPm8LKfAaZ4pAJZ7OQuyPBB2SCXw2SCVL6yXyjaY1WMsiZRPrwVL6tqAhbrmQkLNbXky.7bc7.lzXJJIneGffLMC7EZ3QHPBirTYKUowRslzRQqwSM2V8htx1TqUJEhO3f9p_nH1uzjkD6myjaY2_GGEQIgwe98vDdYejftckuyPBDjaY2ftckZZLQ084akJmZxIFVCqv9_jpidPNs0ojpVMZ90L5H6fqUdHz15tTma1kxNGYjpjV2pNk0ug97SIVb40xN4t23f282p9KyP4yQhSFQ_v9NA14WX3NlY5DuY25BNnOVgw24uy.5f8\"}")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36")
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("X-Apple-Request-Context", "create")
                .addHeader("X-DevTools-Emulate-Network-Conditions-Client-Id", "(2E0AB4265CF3C9E9716F6466BAE7ADDA)")
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("X-Apple-Api-Key", "cbf64fd6843ee630b463f358ea0b707b")
                .addHeader("Referer", "https://appleid.apple.com/account")
                .addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Cookie", "idclient=web; dslang=CN-ZH; site=CHN; aidsp=" + appleCookie.getAidsp() + ";")
                .body(new StringEntity("{\"password\":\"" + appleCookie.getPwd() + "\",\"accountName\":\"" + appleCookie.getEmail() + "\"}", "UTF-8"))
                .execute();
        HttpResponse httpResponse = capTchaResponse.returnResponse();
        appleCookie.setScnt(httpResponse.getHeaders("scnt")[0].getValue());
        if (httpResponse.getStatusLine().getStatusCode() == 204) {
            System.out.println("密码校验通过");
        } else {
            System.out.println("密码校验失败");
            System.exit(0);
        }
    }


    private String verification(String entityStr, AppleCookie appleCookie) throws IOException {
        Response capTchaResponse = Request.Post("https://appleid.apple.com/account/validate")
                .addHeader("User-Agent", "Mozilla/5.0 [en](Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36")
                .addHeader("X-Apple-ID-Session-Id", appleCookie.getAidsp())
                .addHeader("scnt", appleCookie.getScnt())
                .addHeader("Origin", "https://appleid.apple.com")
                .addHeader("X-Apple-I-FD-Client-Info", "{\"U\":\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36\",\"L\":\"zh-CN\",\"Z\":\"GMT+08:00\",\"V\":\"1.1\",\"F\":\"FOa44j1e3NlY5BSo9z4ofjb75PaK4Vpjt.gEngMQEjZrVglE4Ww.GEFF0Yz3ccbbJYMLgiPFU77qZoOSix5ezdstlYysrhsui6.IQnu3xgycUPm8LKfAaZ4pAJZ7OQuyPBB2SCXw2SCVL6yXyjaY1WMsiZRPrwVL6tqAhbrmQkLNbXky.7bc7.lzXJJIneGffLMC7EZ3QHPBirTYKUowRslzRQqwSM2V8htx1TqUJEhO3f9p_nH1uzjkD6myjaY2_GGEQIgwe98vDdYejftckuyPBDjaY2ftckZZLQ084akJmZxIFVCqv9_jpidPNs0ojpVMZ90L5H6fqUdHz15tTma1kxNGYjpjV2pNk0ug97SIVb40xN4t23f282p9KyP4yQhSFQ_v9NA14WX3NlY5DuY25BNnOVgw24uy.5f8\"}")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36")
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("X-Apple-Request-Context", "create")
                .addHeader("X-DevTools-Emulate-Network-Conditions-Client-Id", "(2E0AB4265CF3C9E9716F6466BAE7ADDA)")
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("X-Apple-Api-Key", "cbf64fd6843ee630b463f358ea0b707b")
                .addHeader("Referer", "https://appleid.apple.com/account")
                .addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Cookie", "idclient=web; dslang=CN-ZH; site=CHN; aidsp=" + appleCookie.getAidsp() + ";")
                .body(new StringEntity(entityStr, "UTF-8"))
                .execute();
        HttpResponse httpResponse = capTchaResponse.returnResponse();

        System.out.println(httpResponse.getStatusLine());
        appleCookie.setScnt(httpResponse.getHeaders("scnt")[0].getValue());
        if (httpResponse.getEntity() == null) return null;
        return EntityUtils.toString(httpResponse.getEntity());
    }


    /**
     * 获取会话token & cookie
     *
     * @return
     * @throws IOException
     */
    public String[] getInfo() throws IOException {
        Response acctResponse = Request.Get("https://appleid.apple.com/account#!&page=create")
                .addHeader("User-Agent", "Mozilla/5.0 [en](Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept ", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Connection", "keep-alive")
                .addHeader("Accept-Encoding ", "gzip, deflate, br")
                .addHeader("Connection ", "keep-alive")
                .execute();
        HttpResponse httpResponse = acctResponse.returnResponse();

        System.out.println(httpResponse.getStatusLine());

        String aidsp = httpResponse.getLastHeader("Set-Cookie").getValue();
        aidsp = aidsp.substring(6, aidsp.indexOf(";"));
        String scnt = httpResponse.getHeaders("scnt")[0].getValue();

        return new String[]{aidsp, scnt};
    }

}
